//
//  SafePwdSetViewController.m
//  AppleMarket
//
//  Created by yangy on 09/11/2018.
//  Copyright © 2018 szgsy. All rights reserved.
//

#import "SafePwdSetViewController.h"

// view
#import "BH_UnderLineTextField.h"
// controller
#import "InputCodeViewController.h"
// model
#import "ImageCodeMoel.h"

@interface SafePwdSetViewController ()
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) BH_UnderLineTextField *newPwdTF; // 新资金密码
@property (nonatomic, strong) BH_UnderLineTextField *confirmPwdTF;   // 确认资金密码
@property (nonatomic, strong) BH_UnderLineTextField *codeTF;        // 验证码
@property (nonatomic, strong) UIButton *commitButton;
@property (nonatomic, assign) NSInteger time;
@property (nonatomic, strong) RACDisposable *disposable;

@property (nonatomic, strong) NSString *pwdStr_;
@property (nonatomic, strong) NSString *confirmStr_;
@property (nonatomic, strong) NSString *codeStr_;
@end

@implementation SafePwdSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self initView];
    [self bindViewModel];
}

- (void) bindViewModel
{
    RAC(self,pwdStr_) = _newPwdTF.rac_textSignal;
    RAC(self,confirmStr_) = _confirmPwdTF.rac_textSignal;
    RAC(self,codeStr_) = _codeTF.rac_textSignal;
    
    RAC(_commitButton,enabled) = [RACSignal combineLatest:@[RACObserve(_newPwdTF, text),RACObserve(_confirmPwdTF, text),RACObserve(_codeTF, text)] reduce:^id (NSString *newPwd,NSString *confirmPwd,NSString *code){
        return @(newPwd.length && confirmPwd.length && code.length);
    }];
    RAC(_commitButton,backgroundColor) = [RACSignal combineLatest:@[RACObserve(_newPwdTF, text),RACObserve(_confirmPwdTF, text),RACObserve(_codeTF, text)] reduce:^id (NSString *newPwd,NSString *confirmPwd,NSString *code){
        return (newPwd.length && confirmPwd.length && code.length)? kColorWithHex(0x3291EB) : kColorWithHex(0xADB7C1);
    }];
}

- (void) initView
{
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.newPwdTF];
    [self.view addSubview:self.confirmPwdTF];
    [self.view addSubview:self.codeTF];
    [self.view addSubview:self.commitButton];
    [self setSubviewLayout];
}

- (void) setSubviewLayout
{
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).offset(30);
        make.top.mas_equalTo(self.view).offset(29);
    }];
    
    [_newPwdTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.titleLabel);
        make.right.mas_equalTo(self.view.mas_right).offset(-30);
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(55);
    }];
    
    [_confirmPwdTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.newPwdTF);
        make.right.mas_equalTo(self.newPwdTF);
        make.top.mas_equalTo(self.newPwdTF.mas_bottom).offset(18);
    }];
    
    [_codeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.newPwdTF);
        make.right.mas_equalTo(self.newPwdTF);
        make.top.mas_equalTo(self.confirmPwdTF.mas_bottom).offset(18);
    }];
    
    [_commitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.newPwdTF);
        make.right.mas_equalTo(self.newPwdTF);
        make.height.mas_equalTo(40);
        make.top.mas_equalTo(self.codeTF.mas_bottom).offset(40);
    }];
}

#pragma mark - 发送手机邮箱验证码
- (void) request_SendMsgCode:(NSString*) key code:(NSString*) imageCode
{
    NSString *account = [PlistCommon loginModel].IsMobile? [PlistCommon loginModel].PhoneNumber : [PlistCommon loginModel].Email;
    [SVProgressHUD show];
    [NetRequest request_SendMsgCodeType:@"AddWithdrawAddr" account:account code:imageCode key:key completeHandler:^(id  _Nonnull responseObj) {
        if([[responseObj objectForKey:@"Status"] boolValue]){
            [SVProgressHUD showInfoWithStatus:@"发送成功"];
        }else{
            [SVProgressHUD showInfoWithStatus:[responseObj objectForKey:@"Msg"]];
        }
    } fail:^(NSError * _Nonnull error) {
        [SVProgressHUD showInfoWithStatus:@"网络异常"];
    }];
}

#pragma mark - mark - 设置资金密码
- (void) request_SafePwdSet
{
    [SVProgressHUD show];
    [NetRequest request_DoAuthSafePwd:_pwdStr_ code:_codeStr_ completeHandler:^(id  _Nonnull responseObj) {
        if([[responseObj objectForKey:@"Status"] boolValue]){
            [SVProgressHUD showInfoWithStatus:@"资金密码设置成功"];
            [SVProgressHUD dismissWithDelay:3 completion:^{
                [self.navigationController popToRootViewControllerAnimated:YES];
            }];
        }else{
            [SVProgressHUD showInfoWithStatus:[responseObj objectForKey:@"Msg"]];
        }
    } fail:^(NSError * _Nonnull error) {
        [SVProgressHUD showInfoWithStatus:@"网络异常"];
    }];
}

#pragma mark - lazy load
- (UILabel *)titleLabel
{
    if(!_titleLabel){
        _titleLabel = [UILabel cm_labelWithText:@"设置资金密码" font:kFontBold(26) textColor:kColorWithHex(0x0E304C)];
    }
    return _titleLabel;
}

- (BH_UnderLineTextField *)newPwdTF
{
    if(!_newPwdTF){
        
        _newPwdTF = [[BH_UnderLineTextField alloc] initWithFrame:CGRectMake(30, 0, k_ScreenWidth - 60, 44)];
        _newPwdTF.autocapitalizationType = UITextAutocapitalizationTypeNone;        //首字母不大写
        _newPwdTF.placeholder = @"新资金密码";
        _newPwdTF.font = kFont(13);
        _newPwdTF.secureTextEntry = YES;
        _newPwdTF.errorTextColor = [UIColor redColor];
        //_newPwdTF.keyboardType = UIKeyboardTypeNumberPad;
    }
    return _newPwdTF;
}

- (BH_UnderLineTextField *)confirmPwdTF
{
    if(!_confirmPwdTF){
        _confirmPwdTF = [[BH_UnderLineTextField alloc] initWithFrame:CGRectMake(30, 0, k_ScreenWidth - 60, 44)];
        _confirmPwdTF.autocapitalizationType = UITextAutocapitalizationTypeNone;        //首字母不大写
        _confirmPwdTF.placeholder = @"确认资金密码";
        _confirmPwdTF.font = kFont(13);
        _confirmPwdTF.secureTextEntry = YES;
        _confirmPwdTF.errorTextColor = [UIColor redColor];
        //_confirmPwdTF.keyboardType = UIKeyboardTypeNumberPad;
    }
    return _confirmPwdTF;
}

- (BH_UnderLineTextField *)codeTF
{
    if(!_codeTF){
        _codeTF = [[BH_UnderLineTextField alloc] initWithFrame:CGRectMake(30, 0, k_ScreenWidth - 60, 44)];
        _codeTF.autocapitalizationType = UITextAutocapitalizationTypeNone;        //首字母不大写
        _codeTF.rightViewMode = UITextFieldViewModeAlways;
        _codeTF.rightText = @"获取验证码";
        _codeTF.rightTextColor = kColorWithHex(0x3291EB);
        _codeTF.rightTextFont = kFont(13);
        _codeTF.keyboardType = UIKeyboardTypeNumberPad;
        _codeTF.placeholder = @"验证码";
        _codeTF.font = kFont(13);
        @weakify(self);
        _codeTF.rightHanlder = ^{
            @strongify(self);
            UIButton *sendButton = (UIButton*)self.codeTF.rightView;
            sendButton.enabled = NO;
            self.time = 60;
            self.disposable = [[RACSignal interval:1.0 onScheduler:[RACScheduler mainThreadScheduler]] subscribeNext:^(NSDate * _Nullable x) {
                self.time -- ;
                NSString *title = self.time > 0 ? [NSString stringWithFormat:@"%lds",self.time] : @"重新发送";
                UIColor *bgColor =  self.time > 0 ? kColorWithHex(0xADB7C1) : kColorWithHex(0x3291EB);
                [sendButton setTitle:title forState:UIControlStateNormal | UIControlStateDisabled];
                [sendButton setTitleColor:bgColor forState:UIControlStateNormal | UIControlStateDisabled];
                sendButton.enabled = (self.time <= 0) ? YES : NO;
                if(self.time == 0){
                    [self.disposable dispose];
                }
            }];
            InputCodeViewController *codeVC = [InputCodeViewController inputCodeViewControllerWithCodeType:CodeTypeDoAuthSafePwd];
            codeVC.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.85];
            codeVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            codeVC.completeHandler = ^(ImageCodeMoel * _Nonnull codeModel,NSString *inputCodeStr) {
                [self request_SendMsgCode:codeModel.ImgKey code:inputCodeStr];
            };
            [self presentViewController:codeVC animated:YES completion:nil];
        };
    }
    return _codeTF;
}

- (UIButton *)commitButton
{
    if(!_commitButton){
        _commitButton = [UIButton cm_ButtonWithTitle:@"提交" font:kFont(14) titleColor:[UIColor whiteColor] bgColor:kColorWithHex(0xADB7C1)];
        _commitButton.layer.cornerRadius = 2;
        [[_commitButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if(self.pwdStr_.length < 6 || self.pwdStr_.length > 20){
                self.newPwdTF.error = @"资金密码必须6~20位，包括数字、字母、特殊字符。";
                return ;
            }
            if(self.confirmStr_.length < 6 || self.confirmStr_.length > 20){
                self.confirmPwdTF.error = @"资金密码必须6~20位，包括数字、字母、特殊字符。";
                return ;
            }
            if(![self.pwdStr_ isEqualToString:self.confirmStr_]){
                self.newPwdTF.error = @"两次输入的密码不一致";
                return;
            }
            [self request_SafePwdSet];
        }];
    }
    return _commitButton;
}

@end
